/*
 * 品智科技
 * 按键函数
 */

/* Private includes ----------------------------------------------------------*/
#include "cpu.h"
#include "key.h"
#include "delay.h"

/* Private typedef -----------------------------------------------------------*/

/* Private define ------------------------------------------------------------*/

/* Private macro -------------------------------------------------------------*/

/* Private variables ---------------------------------------------------------*/
_TKS_FLAGA_type keyTrg[2] = {0};
uint8_t         k_count[2];
/* Private function prototypes -----------------------------------------------*/

/* Private user code ---------------------------------------------------------*/

/*0为单次模式 1为连续模式*/
unsigned char KEY_Proc(unsigned char mode) {
    static unsigned char key_up = 1;  // 按键松开标志
    if (mode == 1)
        key_up = 1;  // 支持连按
    // u3_printf("keyup:%d BTN0:%d BTN1:%d\r\n",key_up,BTN0,BTN1);
    if (key_up && (BTN1 == 1 || BTN2 == 1 || BTN3 == 1)) {
        // u3_printf("in key proc\r\n");
        delay_ms(10);
        key_up = 0;
        if (BTN1 == 1)
            return BTN1_PRES;
        else if (BTN2 == 1)
            return BTN2_PRES;
        else if (BTN3 == 1)
            return BTN3_PRES;
    }
    else if (BTN1 == 0 && BTN2 == 0 && BTN3 == 0)
        key_up = 1;
    return 0;  // 无按键按下
}

void keyScan(void) {
    uint8_t        keyRestain = 0, keyData = 0, i, keyDataCur;
    static uint8_t keyDataLast;
    static uint8_t keyTime[keyNUM] = {0};

    keyDataCur = BTN1 | (BTN2 << 1) | (BTN3 << 2);  // 读取按键状态
    keyDataCur &= KEYMASK;                          // 只取低3位,按键数量不超过3个

    if (keyDataCur == keyDataLast) {
        keyData = keyDataCur;  // 保持上次按键状态
    }
    keyDataLast = keyDataCur;  // 记录当前按键状态

    keyTrg[0].byte = keyData & (keyData ^ k_count[0]);
    k_count[0]     = keyData;

    for (i = 0; i < keyNUM; i++) {
        if (k_count[0] & (1 << i)) {
            if (keyTime[i] < RESTAIN_TIMES)
                keyTime[i]++;
            else
                keyRestain |= (1 << i);
        }
        else {
            // if (keyTime[i] > 0) // short press
            //     Key_Up_Trg |= (1 << i);
            // else
            //     Key_Up_Trg &= (~(1 << i));

            keyTime[i] = 0;
            keyRestain &= (~(1 << i));
        }
    }
    keyTrg[1].byte = keyRestain & (keyRestain ^ k_count[1]);
    k_count[1]     = keyRestain;
}
